package com.mar.quarkus.jwt.endpoint;

import com.mar.quarkus.jwt.generator.TokenGenerator;
import com.mar.quarkus.jwt.model.LoginModel;
import com.mar.quarkus.jwt.model.UserModel;
import com.mar.quarkus.jwt.spi.BaseUserModelProvider;
import io.vertx.core.json.JsonObject;
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody;
import org.eclipse.microprofile.openapi.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * Description: 认证端点 .<br>
 *
 * @author m-xy
 *     Created By 2020/4/23 11:16
 */
@Tag(name = "用户认证")
@Path("oauth")
public class TokenEndpoint {
    private final static Logger logger = LoggerFactory.getLogger(TokenEndpoint.class);
    private final List<String> supportedGrantType = Arrays.asList("password");
    @Inject TokenGenerator tokenGenerator;
    @Inject BaseUserModelProvider baseUserModelProvider;

    @POST
    @Path("/token")
    @Operation(summary = "用户登录")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response token(@RequestBody LoginModel loginModel) {
        String grantType = loginModel.getGrantType();
        String userName = loginModel.getUserName();
        String password = loginModel.getPassword();
        if (!supportedGrantType.contains(grantType)) {
            logger.error(String.format("%s grant type is not supported", grantType));
            return Response.status(400)
                .entity(
                    new JsonObject()
                        .put("message", String.format("%s grant type is not supported", grantType))
                ).build();
        }
        UserModel user = baseUserModelProvider.getUserByUserName(userName);
        if (Objects.isNull(user)) {
            logger.error("user not found:{}", userName);
            return Response.status(400).entity(new JsonObject().put("message", "用户不存在")).build();
        }
        if (!baseUserModelProvider.checkPassword(user, password)) {
            return Response.status(400).entity(new JsonObject().put("message", "用户名或密码错误")).build();
        }
        JsonObject jsonObject = tokenGenerator.generateTokenString(user.getUserId(), user.getUserName(),
            user.getRoles());
        return Response.ok(jsonObject).build();
    }
}
